'use client';

import { useState, useEffect } from 'react';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import GlassInput from '@/components/ui/GlassInput';
import { CheckCircle, XCircle, RefreshCw, Save, Server } from 'lucide-react';
import toast from 'react-hot-toast';

interface OllamaModel {
  name: string;
  size: number;
  modified_at: string;
}

interface ModelConfig {
  llm_model: string;
  embedding_model: string;
  ollama_base_url: string;
  temperature: number;
  max_tokens: number;
}

export default function SettingsPage() {
  const [loading, setLoading] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [models, setModels] = useState<OllamaModel[]>([]);
  const [config, setConfig] = useState<ModelConfig>({
    llm_model: 'qwen2.5:7b',
    embedding_model: 'nomic-embed-text',
    ollama_base_url: 'http://localhost:11434',
    temperature: 0.7,
    max_tokens: 2000,
  });

  useEffect(() => {
    loadConfig();
    loadModels();
  }, []);

  const loadConfig = async () => {
    try {
      const { modelsApi } = await import('@/lib/api');
      const response = await modelsApi.getConfig();
      setConfig(response);
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  };

  const loadModels = async () => {
    try {
      const { modelsApi } = await import('@/lib/api');
      const response = await modelsApi.list();
      setModels(response.models || []);
    } catch (error) {
      console.error('加载模型列表失败:', error);
    }
  };

  // 获取LLM模型列表（排除embedding模型）
  const getLlmModels = () => {
    return models.filter(m => 
      !m.name.includes('embed') && 
      !m.name.includes('embedding')
    );
  };

  // 获取Embedding模型列表
  const getEmbeddingModels = () => {
    const embedModels = models.filter(m => 
      m.name.includes('embed') || 
      m.name.includes('embedding')
    );
    // 如果没有embedding模型，返回所有模型
    return embedModels.length > 0 ? embedModels : models;
  };

  const testConnection = async () => {
    setTesting(true);
    setTestResult(null);
    try {
      const { modelsApi } = await import('@/lib/api');
      const result = await modelsApi.testConnection();
      setTestResult(result);
      if (result.success) {
        // 重新加载模型列表
        await loadModels();
      }
    } catch (error: any) {
      setTestResult({
        success: false,
        message: error.message || '连接测试失败',
      });
    } finally {
      setTesting(false);
    }
  };

  const saveConfig = async () => {
    setLoading(true);
    try {
      const { modelsApi } = await import('@/lib/api');
      await modelsApi.updateConfig(config);
      toast.success('配置保存成功！');
    } catch (error: any) {
      toast.error('保存失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const formatSize = (bytes: number) => {
    const gb = bytes / (1024 * 1024 * 1024);
    return gb.toFixed(2) + ' GB';
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-extrabold">
          <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
            系统设置
          </span>
        </h1>
      </div>

      {/* Ollama连接测试 */}
      <GlassCard className="p-6 border border-gray-200/60 dark:border-white/20">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent dark:from-white dark:to-gray-200 mb-1">Ollama 服务</h2>
            <p className="text-gray-500 dark:text-white/60 text-sm">测试 Ollama 服务连接状态</p>
          </div>
          <GlassButton
            onClick={testConnection}
            loading={testing}
            variant="secondary"
            size="md"
          >
            {testing ? <RefreshCw className="mr-2 h-4 w-4 animate-spin" /> : <Server className="mr-2 h-4 w-4" />}
            测试连接
          </GlassButton>
        </div>

        {testResult && (
          <div
            className={`flex items-center gap-3 p-4 rounded-lg ${
              testResult.success
                ? 'bg-green-500/20 border border-green-400/30'
                : 'bg-red-500/20 border border-red-400/30'
            }`}
          >
            {testResult.success ? (
              <CheckCircle className="h-5 w-5 text-green-400" />
            ) : (
              <XCircle className="h-5 w-5 text-red-400" />
            )}
            <span className="text-gray-900 dark:text-white/90">{testResult.message}</span>
          </div>
        )}
      </GlassCard>

      {/* 可用模型列表 */}
      <GlassCard className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">可用模型</h2>
          <GlassButton onClick={loadModels} variant="ghost" size="sm">
            <RefreshCw className="mr-2 h-4 w-4" />
            刷新
          </GlassButton>
        </div>

        {models.length === 0 ? (
          <p className="text-gray-500 dark:text-white/60 text-center py-8">
            暂无可用模型，请先安装 Ollama 并下载模型
          </p>
        ) : (
          <div className="space-y-2">
            {models.map((model) => (
              <div
                key={model.name}
                className="flex items-center justify-between p-4 rounded-lg bg-gray-100/50 dark:bg-white/5 hover:bg-gray-200/50 dark:hover:bg-white/10 transition-colors"
              >
                <div>
                  <p className="text-gray-900 dark:text-white font-medium">{model.name}</p>
                  <p className="text-gray-500 dark:text-white/60 text-sm">
                    {formatSize(model.size)} • 更新于 {new Date(model.modified_at).toLocaleString('zh-CN')}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </GlassCard>

      {/* 模型配置 */}
      <GlassCard className="p-6 border border-gray-200/60 dark:border-white/20">
        <h2 className="text-xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent dark:from-white dark:to-gray-200 mb-6">模型配置</h2>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 dark:text-white/90 mb-2">
              LLM 模型
            </label>
            <select
              value={config.llm_model}
              onChange={(e) => setConfig({ ...config, llm_model: e.target.value })}
              className="w-full px-4 py-3 bg-white/60 dark:bg-white/10 backdrop-blur-md backdrop-saturate-150 border border-gray-300/40 dark:border-white/20 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40 dark:focus:ring-white/30 shadow-sm"
            >
              <option value="" disabled className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">选择模型</option>
              {getLlmModels().map((model) => (
                <option key={model.name} value={model.name} className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                  {model.name}
                </option>
              ))}
              <option value="custom" className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">自定义...</option>
            </select>
            {config.llm_model === 'custom' && (
              <input
                type="text"
                placeholder="输入模型名称，如: qwen2.5:32b"
                onChange={(e) => setConfig({ ...config, llm_model: e.target.value })}
                className="w-full px-4 py-3 mt-2 bg-white/40 dark:bg-white/10 backdrop-blur-md border border-gray-300/50 dark:border-white/20 rounded-lg text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500/50 dark:focus:ring-white/30"
              />
            )}
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 dark:text-white/90 mb-2">
              Embedding 模型
            </label>
            <select
              value={config.embedding_model}
              onChange={(e) => setConfig({ ...config, embedding_model: e.target.value })}
              className="w-full px-4 py-3 bg-white/60 dark:bg-white/10 backdrop-blur-md backdrop-saturate-150 border border-gray-300/40 dark:border-white/20 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40 dark:focus:ring-white/30 shadow-sm"
            >
              <option value="" disabled className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">选择模型</option>
              {getEmbeddingModels().map((model) => (
                <option key={model.name} value={model.name} className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                  {model.name}
                </option>
              ))}
              <option value="custom" className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">自定义...</option>
            </select>
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              📌 只显示包含 "embed" 的模型，推荐: nomic-embed-text
            </p>
          </div>

          <GlassInput
            label="Ollama 服务地址"
            value={config.ollama_base_url}
            onChange={(e) => setConfig({ ...config, ollama_base_url: e.target.value })}
            placeholder="http://localhost:11434"
          />

          <div className="grid grid-cols-2 gap-4">
            <div>
              <GlassInput
                label="温度参数 (0-2)"
                type="number"
                step="0.1"
                min="0"
                max="2"
                value={config.temperature}
                onChange={(e) => setConfig({ ...config, temperature: parseFloat(e.target.value) })}
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-white/50">
                控制输出随机性。值越低越确定，越高越有创意。推荐 0.7
              </p>
            </div>

            <GlassInput
              label="最大 Token 数"
              type="number"
              step="100"
              min="100"
              max="32000"
              value={config.max_tokens}
              onChange={(e) => setConfig({ ...config, max_tokens: parseInt(e.target.value) })}
            />
          </div>

          <div className="flex justify-end pt-4">
            <GlassButton
              onClick={saveConfig}
              loading={loading}
              variant="primary"
              size="lg"
            >
              <Save className="mr-2 h-5 w-5" />
              保存配置
            </GlassButton>
          </div>
        </div>
      </GlassCard>
    </div>
  );
}

